/*jslint vars: true, forin: true, sloppy: true */
/*global angular, ocDialog, DialogManager, DialogFactory */
ocDialog.directive('ocAddress', function ($interval) {
	return {
		template:
			'<div class="oc-address">' +
				'<input ng-model="address" ng-focus="isManual=true" ' +
					'ng-disabled="isCross" ' +
					'ng-keydown="gotoUrl($event)" />' +
				'<button class="reset" ng-click="reset()" ng-show="isCross"></button>' +
				'<button class="goto" ng-click="gotoUrl($event)" ' +
					'ng-mousedown="isManual=false" ng-hide="isCross"></button>' +
				'<button class="refresh" ng-click="refresh()" ' +
					'ng-mousedown="isManual=false" ng-hide="isCross||isManual"></button></div>',
		restrict: 'E',
		replace: true,
		scope: {
			iframe: '=ocAddressIframe'
		},
		link: function (scope, element, attr) {
			scope.isCross = false;
			scope.isManual = false;

			// Refresh address per 1s.
			function refreshAddress() {
				try {
					if (!scope.isManual) {
						scope.address = scope.iframe.contentWindow.location.href;
						scope.isCross = false;
					}
				} catch (errorCrossDomain) {
					scope.isCross = true;
					scope.address = '正在跨域';
				}
			};
			$interval(refreshAddress, 600);

			// Jump page button.
			scope.gotoUrl = function (event) {

				if (event.which === 1 || event.which === 13) {
					event.target.blur();
					scope.iframe.src = scope.address;
					scope.isManual = false;
				}
			};

			// Refresh page button.
			scope.refresh = function () {
				scope.iframe.contentWindow.location.reload();
			};

			// Reset src to '/' when iframe in cross-domain.
			scope.reset = function () {
				scope.isCross = false;
				scope.iframe.src = '/';
			};
			
			scope.$watch('iframe', function () {
				if (scope.iframe instanceof HTMLIFrameElement) {
					refreshAddress();
				}
			});
		}
	};
});
